package xdu.lz.protocol.dubbo;

import xdu.lz.framework.RequestWrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * netty收到服务器响应后，进入
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter
        implements Callable {

    private ChannelHandlerContext context;
    private RequestWrap requestWrap;
    private String result;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        notify();
    }


    /**
     * 提交给线程池执行
     * @return
     * @throws Exception
     */
    public synchronized Object call() throws Exception {
        context.writeAndFlush(this.requestWrap);
        wait();
        return result;
    }

    /**
     * 封装结果
     * @param requestWrap
     */
    public void setRequestWrap(RequestWrap requestWrap) {
        this.requestWrap = requestWrap;
    }
}
